import {Directive} from 'vue'

function randomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

export default {
    // 可控制滚动速度，默认滚动速度20px/s,最低动画时长2s
    mounted: (el, binding, vNode) => {
        el.style.overflow = 'hidden'
        el.style.whiteSpace = 'nowrap'
        // const speed = binding.value || 10;
        el.__span__ = document.createElement('span')
        el.__span__.innerHTML = vNode.children[0].children
        el.innerHTML = ''
        el.appendChild(el.__span__)
        // console.log('binding', binding.value)
        let Animationid = binding.value;
        // 滚动
        el.isRoll = () => {
            // const speed = el.__span__.offsetWidth / 5;
            if (el.__span__.offsetWidth > el.offsetWidth) {
                // console.log('offsetWidth',el.__span__.offsetWidth)
                //移动速度（秒）
                const times = Math.max( //找最大值
                    Number(el.__span__.offsetWidth) / 60,
                    10
                )
                let offsetleft = el.__span__.offsetWidth - 150;
                let mymove = `@keyframes ${Animationid} { 
                    0% { transform: translate(0px, 0); } 
                    100% { 
                        transform: translate(-${offsetleft}px, 0);
                        animation-delay: 1s; 
                    } 
                }`;
                const style = document.createElement('style');
                style.setAttribute('type', 'text/css')
                document.head.appendChild(style)
                style.sheet.insertRule(mymove, 0)
                el.__span__.style.float = 'left';
                el.__span__.style.textAlign = 'left';
                let num = randomInt(1, 4);
                console.log('num', times)
                // console.log('style', document.head)
                el.__span__.style.animation = ` ${Animationid} linear ${times}s ${num}s infinite normal forwards`

            } else {
                el.__span__.style.float = 'none'
                el.__span__.style.animation = 'none'
            }
        }
        el.__observe__ = new ResizeObserver(el.isRoll)
        el.__observe__.observe(el, {box: 'border-box'})
    },
    updated: (el, _, vNode) => {
        el.__span__.innerText = vNode.children[0].children
        el.isRoll()
    },
    unmounted: (el) => {
        el.__observe__.disconnect()
    },
}